<template>
	<el-drawer direction="rtl" v-model="dialogVisible" :title="dialogTitle" size="90%">
		<el-form ref="formRef" v-loading="formLoading" :model="formData" :rules="formRules" label-width="120px">
			<el-row>
				<el-col :span="12">
					<el-form-item label="所属社区" prop="commId">
						<el-tree-select v-model="formData.commId" :data="communityTree" :props="defaultProps" check-strictly default-expand-all placeholder="请选择所属社区" value-key="id" />
					</el-form-item>
				</el-col>
				<el-col :span="12">
					<el-form-item label="模式" prop="modeFlag">
						<el-select v-model="formData.modeFlag">
							<el-option v-for="dict in modeFlags" :key="dict.value" :label="dict.label" :value="dict.value" />
						</el-select>
					</el-form-item>
				</el-col>
			</el-row>
			<el-row>
				<el-col :span="12">
					<el-form-item label="电表名称" prop="meterName">
						<el-input v-model="formData.meterName" placeholder="请输入电表名称" />
					</el-form-item>
				</el-col>
				<el-col :span="12">
					<el-form-item label="电表编码" prop="meterNo">
						<el-input v-model="formData.meterNo" placeholder="请输入电表编码" />
					</el-form-item>
				</el-col>
			</el-row>
			<el-form-item label="对应集中器" prop="meterSerialServerId">
				<el-input v-model="formData.meterSerialServerName_" :readonly="true">
					<template #append>
						<el-button icon="el-icon-search" @click="openSelectSerialServer">选择</el-button>
						<el-button type="success" @click="clearSelectSerialServer">清空</el-button>
					</template>
				</el-input>
				<div style="color: gray">若电表厂家是弘新能源且电表自带网络功能，请选择</div>
				<span style="color: red">“弘能虚拟集中器”</span>
			</el-form-item>
			<el-form-item label="电表型号" prop="productId" v-if="needProductFlag">
				<el-input v-model="formData.productName_" :readonly="true">
					<template #append>
						<el-button icon="el-icon-search" @click="openProductDict">选择</el-button>
						<el-button type="success" @click="clearProductDict">清空</el-button>
					</template>
				</el-input>
				<div style="color: gray">若电表厂家是弘新能源则需要选择具体的电表型号</div>
			</el-form-item>
			<el-form-item label="分账账户" prop="matCodeId">
				<el-input v-model="formData.matConfigRemark_" :readonly="true">
					<template #append>
						<el-button icon="el-icon-search" @click="openMat">选择</el-button>
						<el-button type="success" @click="clearMat">清空</el-button>
					</template>
				</el-input>
			</el-form-item>
			<el-row>
				<el-col :span="12">
					<el-form-item label="使用状态" prop="useStatus">
						<el-select v-model="formData.useStatus">
							<el-option v-for="dict in getStrDictOptions(DICT_TYPE.METER_USE_STATUS)" :key="dict.value" :label="dict.label" :value="dict.value" />
						</el-select>
					</el-form-item>
				</el-col>
				<el-col :span="12">
					<el-form-item label="用电上报" prop="reportFlag">
						<el-radio-group v-model="formData.reportFlag">
							<el-radio v-for="dict in getIntDictOptions(DICT_TYPE.METER_REPORT_FLAG)" :key="dict.value" :label="dict.value">
								{{ dict.label }}
							</el-radio>
						</el-radio-group>
					</el-form-item>
				</el-col>
			</el-row>
			<el-form-item label="排序" prop="sort">
				<el-input v-model="formData.sort" placeholder="请输入排序" />
			</el-form-item>
			<el-form-item label="外系统关联id">
				<el-input v-model="formData.externalLinkId" placeholder="请输入外系统关联id" />
			</el-form-item>
		</el-form>
		<template #footer>
			<el-button type="primary" @click="submitForm">确 定</el-button>
			<el-button @click="dialogVisible = false">取 消</el-button>
		</template>
	</el-drawer>
	<OwnMeterConfigSelect ref="ownMeterConfigSelectRef" @confirm-own-meter-config="confirmOwnMeterConfig" />
	<MeterSerialServerSelect ref="meterSerialServerSelectRef" @confirm-serial-server="confirmSerialServer" />
	<HxnyProductDict ref="hxnyProductDictRef" @confirm-product-dict="confirmProductDict" />
</template>
<script lang="ts" setup>
	import { DICT_TYPE, getIntDictOptions, getStrDictOptions } from '@/utils/dict'
	import { defaultProps, handleTree } from '@/utils/tree'
	import * as MeterApi from '@/api/zwsj/meter'
	import * as MeterSerialServerApi from '@/api/zwsj/meterSerialServer'
	import * as CommunityApi from '@/api/zwsj/community'
	import OwnMeterConfigSelect from '@/views/zwsj/common/OwnMeterConfigSelect.vue'
	import MeterSerialServerSelect from '@/views/zwsj/common/MeterSerialServerSelect.vue'
	import HxnyProductDict from '@/views/zwsj/common/HxnyProductDict.vue'

	defineOptions({ name: 'MeterForm' })

	const { t } = useI18n() // 国际化
	const message = useMessage() // 消息弹窗

	const modeFlags = getIntDictOptions(DICT_TYPE.METER_MODE_FLAG)
	const dialogVisible = ref(false) // 弹窗的是否展示
	const dialogTitle = ref('') // 弹窗的标题
	const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
	const formType = ref('') // 表单的类型：create - 新增；update - 修改
	const formData = ref({
		id: undefined,
		commId: undefined,
		meterSerialServerId: undefined,
		meterSerialServerName_: undefined,
		modeFlag: undefined,
		productId: undefined,
		productName_: undefined,
		meterName: undefined,
		meterNo: undefined,
		externalLinkId: undefined,
		useStatus: undefined,
		reportFlag: undefined,
		sort: undefined,
		serialServer: {
			id: undefined,
			serialServerName: undefined,
		},
		matCodeId: undefined,
		matConfigRemark_: undefined,
		ownMeterConfigRespVO: {
			configRemark: undefined,
		},
	})
	const formRules = reactive({
		commId: [
			{
				required: true,
				message: '社区不能为空',
				trigger: 'blur',
			},
		],
		modeFlag: [
			{
				required: true,
				message: '电表使用模式不能为空',
				trigger: 'blur',
			},
		],
		meterName: [
			{
				required: true,
				message: '电表名称不能为空',
				trigger: 'blur',
			},
		],
		meterNo: [
			{
				required: true,
				message: '电表编码不能为空',
				trigger: 'blur',
			},
		],
		useStatus: [
			{
				required: true,
				message: '电表使用状态不能为空',
				trigger: 'blur',
			},
		],
		sort: [
			{
				required: true,
				message: '排序不能为空',
				trigger: 'blur',
			},
		],
	})
	const formRef = ref() // 表单 Ref
	const communityTree = ref() // 树形结构
	const needProductFlag = ref(false)

	/** 打开弹窗 */
	const open = async (type: string, id?: number, commId?: number) => {
		dialogVisible.value = true
		dialogTitle.value = t('action.' + type)
		formType.value = type
		resetForm()

		//设置区域默认值
		if (undefined != commId) {
			let commData = await CommunityApi.getCommunity(commId)
			if (true == commData.villageSign) {
				formData.value.commId = commId
			}
		}
		// 修改时，设置数据
		if (id) {
			formLoading.value = true
			try {
				if (type === 'update') {
					let data = await MeterApi.getMeter(id)
					formData.value = data
					if (formData.value.serialServer && formData.value.serialServer != null) {
						formData.value.meterSerialServerName_ = formData.value.serialServer.serialServerName
					}
					if (formData.value.ownMeterConfigRespVO && formData.value.ownMeterConfigRespVO != null) {
						formData.value.matConfigRemark_ = formData.value.ownMeterConfigRespVO.configRemark
					}

					//需要判断出集中器厂家，根据集中器厂家判断是否需要显示设备型号
					needProductFlag.value = false
					if (formData.value.meterSerialServerId) {
						const serialServer = await MeterSerialServerApi.getMeterSerialServer(formData.value.meterSerialServerId)
						if (serialServer.factoryCode == '1') {
							needProductFlag.value = true
						}
					}
				}
			} finally {
				formLoading.value = false
			}
		} else {
			formData.value.modeFlag = 0
			formData.value.useStatus = 'enable'
			formData.value.reportFlag = 1
		}
		// 获得社区树
		await getTree()
	}
	defineExpose({ open }) // 提供 open 方法，用于打开弹窗

	/** 提交表单 */
	const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
	const submitForm = async () => {
		// 校验表单
		if (!formRef) return
		const valid = await formRef.value.validate()
		if (!valid) return
		// 提交请求
		formLoading.value = true
		try {
			const data = formData.value as unknown as MeterApi.MeterVo
			if (formType.value === 'create') {
				await MeterApi.createMeter(data)
				message.success(t('common.createSuccess'))
			} else {
				await MeterApi.updateMeter(data)
				message.success(t('common.updateSuccess'))
			}
			dialogVisible.value = false
			// 发送操作成功的事件
			emit('success')
		} finally {
			formLoading.value = false
		}
	}

	/** 重置表单 */
	const resetForm = () => {
		formData.value = {
			id: undefined,
			commId: undefined,
			meterSerialServerId: undefined,
			meterSerialServerName_: undefined,
			modeFlag: undefined,
			productId: undefined,
			productName_: undefined,
			meterName: undefined,
			meterNo: undefined,
			externalLinkId: undefined,
			useStatus: undefined,
			reportFlag: undefined,
			sort: undefined,
			serialServer: {
				id: undefined,
				serialServerName: undefined,
			},
			matCodeId: undefined,
			matConfigRemark_: undefined,
			ownMeterConfigRespVO: {
				configRemark: undefined,
			},
		}
		formRef.value?.resetFields()
	}

	/** 获得区域树 */
	const getTree = async () => {
		communityTree.value = []
		const data = await CommunityApi.listSimpleCommunitys()
		let community: Tree = { id: 0, name: '顶级区域', children: [] }
		community.children = handleTree(data)
		communityTree.value.push(community)
	}

	// 选择集中器
	const meterSerialServerSelectRef = ref()
	const openSelectSerialServer = async () => {
		let commId = formData.value.commId
		meterSerialServerSelectRef.value.open(commId)
	}

	const confirmSerialServer = async serverInfo => {
		formData.value.meterSerialServerName_ = serverInfo.serialServerName
		formData.value.meterSerialServerId = serverInfo.id

		needProductFlag.value = false
		formData.value.productId = undefined
		const serialServer = await MeterSerialServerApi.getMeterSerialServer(formData.value.meterSerialServerId)
		if (serialServer.factoryCode == '1') {
			needProductFlag.value = true
		}
	}
	const clearSelectSerialServer = async () => {
		formData.value.meterSerialServerName_ = undefined
		formData.value.meterSerialServerId = undefined
	}

	// 选择分账功能
	const ownMeterConfigSelectRef = ref()
	const openMat = async () => {
		ownMeterConfigSelectRef.value.open()
	}
	const confirmOwnMeterConfig = async ({ matCode }) => {
		formData.value.matConfigRemark_ = matCode.configRemark
		formData.value.matCodeId = matCode.id
	}
	const clearMat = async () => {
		formData.value.matConfigRemark_ = undefined
		formData.value.matCodeId = undefined
	}

	// 选择弘新能源电表型号
	const hxnyProductDictRef = ref()
	const openProductDict = async () => {
		hxnyProductDictRef.value.open()
	}
	const confirmProductDict = async dict => {
		console.info(dict)
		formData.value.productName_ = dict.name
		formData.value.productId = dict.id
	}
	const clearProductDict = async () => {
		formData.value.productName_ = undefined
		formData.value.productId = undefined
	}
</script>
